﻿using Business.Service;
using Model;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace MvcAppWeb.Controllers
{
    public class PrintOrderInfoController : BaseDataController
    {
        //
        // GET: /PrintOrderInfo/
        public ActionResult PrintOrderInfo()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);

            }
        }

        ///<summary>
        ///查询订单打印信息
        ///</summary>
        ///<returns></returns>
        public JsonResult InitJsonResult(string startDate, string OrderNo = "", string selArea = "0", string batchno = "0", string OrderStatus = "0",
            string OrderFrom = "", string OrderEnd = "", string GOODSCODE = "")
        {

            string where = " where 1=1 and t2.saleorderflag in(1,2,5,6) and t2.SiteID<>0";
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;

            if (startDate != "")
            {
                DateTime RationDate;
                if (DateTime.TryParse(startDate, out RationDate))
                {
                    where += " and t1.rationdate=to_date('" + RationDate.ToString("yyyy-MM-dd") + "','yyyy-mm-dd') ";
                }
                else
                    where += " and 1=0";
            }
            if (OrderNo != "")
            {
                where += "   and t1.orderno='" + OrderNo + "'";
            }
            if (!selArea.Equals("0"))
            {
                where += " and t2.siteid='" + selArea.Trim() + "' ";
            }
            if (!batchno.Equals("0") && !string.IsNullOrEmpty(batchno))
            {
                where += " and t1.batch_no='" + batchno + "' ";
            }
            int orderFrom_End = 0;
            if (int.TryParse(OrderFrom, out orderFrom_End))
            {
                where += " and t1.batch_subno>=" + OrderFrom;
            }
            if (int.TryParse(OrderEnd, out orderFrom_End))
            {
                where += " and t1.batch_subno<=" + OrderEnd;
            }
            if (!string.IsNullOrEmpty(GOODSCODE))
            {
                GOODSCODE = GOODSCODE.Substring(0, GOODSCODE.Length - 1);
                where += " and exists(select 1 from wcs.p_indent_det t3 where t3.orderno = t2.sheetid and t3.itemcode in(" + GOODSCODE + "))";
            }
            //if (!batchno.Equals("0"))
            //{
            //    where += " and a.batchno in (" + batchno + ") ";
            //}
            //if (!paytype.Equals("0"))
            //{
            //    where += " and a.CUSTOMERPAYTYPE='" + paytype + "' ";
            //}
            //if (!Isprint.Equals("0"))
            //{
            //    if (Isprint == "1")//1为已打印2未打印
            //        where += " and NVL(d.printcount,0)>0 ";
            //    else
            //        where += " and NVL(d.printcount,0)<=0 ";
            //}
            if (!OrderStatus.Equals("0"))
            {
                if (OrderStatus == "1")//1为未取消2已取消
                    where += " and t2.saleorderflag<>2 ";
                else
                    where += " and t2.saleorderflag=2 ";
            }
            where += " order by to_number(t1.batch_no),t1.batch_subno ";

            var retData = new object();
            BPrintOrderInfo db = new BPrintOrderInfo();
            retData = db.GetPrintDPSOrderList(page, rows, out total, where).ToList();
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", retData);
            return Json(json);
        }

        [HttpPost]
        public string ExporterExcelDetail(string RationStartDate, string OrderNo = "", string DeliverArea = "0", string selBatch = "0",
            string OrderStatus = "0", string OrderFrom = "", string OrderEnd = "", string GOODSCODE = "", string Ispreview = "0")
        {
            string sjson = string.Empty;
            //selBatch = string.IsNullOrEmpty(selBatch) ? "0" : selBatch;
            BPrintOrderInfo db = new BPrintOrderInfo();
            DateTime RationDate;
            if (DateTime.TryParse(RationStartDate, out RationDate))
            {
                RationStartDate = RationDate.ToString("yyyy-MM-dd");
            }
            int intOrderFrom = 0;
            int intOrderEnd = 0;
            if (int.TryParse(OrderFrom, out intOrderFrom)) { }
            if (int.TryParse(OrderEnd, out intOrderEnd)) { }
            GOODSCODE = Request["hiddenGOODSCODE"];

            string where = " where 1=1 and t2.saleorderflag in(1,2,5,6) and t2.SiteID<>0";
            string where1 = " where 1=1 and t2.saleorderflag in(1,2,5,6) and t2.SiteID<>0";

            if (RationStartDate != "")
            {
                DateTime RationDate1;
                if (DateTime.TryParse(RationStartDate, out RationDate1))
                {
                    where += " and t1.rationdate=to_date('" + RationDate1.ToString("yyyy-MM-dd") + "','yyyy-mm-dd') ";
                    where1 += " and t1.rationdate=to_date('" + RationDate1.ToString("yyyy-MM-dd") + "','yyyy-mm-dd') ";
                }
                else
                {
                    where += " and 1=0";
                    where1 += " and 1=0";
                }
            }
            if (OrderNo != "")
            {
                where += "   and t1.orderno='" + OrderNo + "'";
                where1 += "   and t1.orderno='" + OrderNo + "'";
            }
            if (!DeliverArea.Equals("0"))
            {
                where += " and t2.siteid='" + DeliverArea.Trim() + "' ";
                where1 += " and t2.siteid='" + DeliverArea.Trim() + "' ";
            }
            if (!selBatch.Equals("0") && !string.IsNullOrEmpty(selBatch))
            {
                where += " and t1.batch_no='" + selBatch + "' ";
                where1 += " and t1.batch_no='" + selBatch + "' ";
            }
            int orderFrom_End = 0;
            if (int.TryParse(OrderFrom, out orderFrom_End))
            {
                where += " and t1.batch_subno>=" + OrderFrom;
                where1 += " and t1.batch_subno>=" + OrderFrom;
            }
            if (int.TryParse(OrderEnd, out orderFrom_End))
            {
                where += " and t1.batch_subno<=" + OrderEnd;
                where1 += " and t1.batch_subno<=" + OrderEnd;
            }
            if (!string.IsNullOrEmpty(GOODSCODE))
            {
                GOODSCODE = GOODSCODE.Substring(0, GOODSCODE.Length - 1);
                where += " and exists(select 1 from wcs.p_indent_det pi where pi.orderno = t1.orderno and pi.itemcode in(" + GOODSCODE + "))";
                where1 += " and pi.itemcode in(" + GOODSCODE + ")";
            }
            if (!OrderStatus.Equals("0"))
            {
                if (OrderStatus == "1")//1为未取消2已取消
                {
                    where += " and t2.saleorderflag<>2 ";
                    where1 += " and t2.saleorderflag<>2 ";
                }
                else
                {
                    where += " and t2.saleorderflag=2 ";
                    where1 += " and t2.saleorderflag=2 ";
                }
            }
            where += " order by to_number(t1.batch_no),t1.batch_subno ";
            List<PrintOrderInfo> lstPrintOrderInfo = db.GetPrintDPSOrderList(where).ToList();
            List<OrderInfoDetail> listDetail = db.GetPrintDPSOrderDetailList(where1).ToList();
            //List<PrintOrderInfo> lstPrintOrderInfo = db.GetPrintDPSOrderList(RationStartDate, OrderNo, DeliverArea, selBatch, OrderStatus, intOrderFrom, intOrderEnd).ToList();
            //List<OrderInfoDetail> listDetail = db.GetPrintDPSOrderDetailList(RationStartDate, OrderNo, DeliverArea, selBatch, OrderStatus, intOrderFrom, intOrderEnd).ToList();
            if (listDetail.Where(_ => string.IsNullOrEmpty(_.GOODSCODE)).Count() > 0)
            {
                return "{success:false,msg:'配方同步中，请过五分钟再操作'}";
            }

            if (lstPrintOrderInfo.Count <= 0)
                return "{success:false,msg:'没有符合条件的订单'}";
            foreach (PrintOrderInfo item in lstPrintOrderInfo)
            {
                item.SaleOrderItem = listDetail.Where(_ => _.SHEETID == item.SHEETID).ToList();
                item.TOTALQTY = listDetail.Where(_ => _.SHEETID == item.SHEETID).Sum(_ => _.QTY);
            }
            List<OrderInfo_Print_His> lstOrderInfo_Print_His = GetOrderInfo_Print_His(lstPrintOrderInfo);
            if (Ispreview == "1")//预览不打印
            {
                string strPrintOrderInfo = JsonConvert.SerializeObject(lstPrintOrderInfo[0]);
                sjson = "{success:true,msg:'',info:" + strPrintOrderInfo + "}";
                return sjson;
            }
            int AreaCount = lstPrintOrderInfo.Count(_ => string.IsNullOrEmpty(_.DISTRICT));
            if (AreaCount > 0)
                return "{success:false,msg:'有" + AreaCount + "张订单没有匹配的配送区域,如：" + lstPrintOrderInfo.Where(_ => string.IsNullOrEmpty(_.DISTRICT)).ToList()[0].SHEETID + "'}";
            if (db.AddOrderInfoPrintHis(lstOrderInfo_Print_His))
            {
                string strPrintOrderInfo = JsonConvert.SerializeObject(lstPrintOrderInfo);
                sjson = "{success:true,msg:'',info:" + strPrintOrderInfo + "}";
            }
            else
                sjson = "{success:false,msg:'执行失败'}";

            return sjson;
        }

        public List<OrderInfo_Print_His> GetOrderInfo_Print_His(List<PrintOrderInfo> lstPrintOrderInfo)
        {
            AppUserList model = (AppUserList)Session["UserInfo"];
            List<OrderInfo_Print_His> lstOrderInfo_Print_His = new List<OrderInfo_Print_His>();
            foreach (PrintOrderInfo _PrintOrderInfo in lstPrintOrderInfo)
            {
                OrderInfo_Print_His _OrderInfo_Print_His = new OrderInfo_Print_His();
                _OrderInfo_Print_His.ORDERNO = _PrintOrderInfo.SHEETID;
                _OrderInfo_Print_His.PRINTUSERID = model.USERID;
                _OrderInfo_Print_His.PRINTUSERNAME = model.USERNAME;
                _OrderInfo_Print_His.PRINTDATE = DateTime.Now;
                lstOrderInfo_Print_His.Add(_OrderInfo_Print_His);
            }
            return lstOrderInfo_Print_His;
        }

    }
}
